/**
 * http请求方法封装
 * @param options:{
 *     url:url,
 *     method:"",//[get,post,put,delete],
 *     params:params,
 *     body:body,
 *     async:true||false,
 *     headers:{
 *         "Content-type","application/x-www-form-urlencoded",
 *         "token:""
 *     }
 * }
 * @param callback:function callback(){}
 */
function httpRequest(options,callback) {
    const {url,method,params,data,headers,async = true} = options
    let xmlhttp = null;
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }else{
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //建立连接
    xmlhttp.open(method,url,async);
    //设置请求头
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

    //发送请求（string在post时使用）
    if (method.toUpperCase() !== "GET") {
        let arr=[];
        for (const attr in data) {
            arr.push(encodeURIComponent(attr)+"="+encodeURIComponent(data[attr]));
        }
        const str = arr.join("&");
        xmlhttp.send(str);
    } else {
        xmlhttp.send()
    }
    //接收响应信息
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState===4 && xmlhttp.status === 200){
            //响应的数据
            callback(xmlhttp.responseText)
        } else {
            callback(xmlhttp.status)
        }
    }
}

// function callback(responseText) {
//     alert(responseText)
// }
